package com.kh.statistics.video.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kh.statistics.video.base.ClientEnum;
import com.kh.statistics.video.config.RedisService;
import com.kh.statistics.video.constant.AccountsConstant;
import com.kh.statistics.video.entity.VideoAccountsHealth;
import com.kh.statistics.video.service.VideoAccountsHealthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @BelongsProject: statistics
 * @BelongsPackage: com.kh.statistics.video.service.impl
 * @Author: Hong.Kong
 * @CreateTime: 2024-05-24  16:47
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class VideoAccountsHealthServiceImpl implements VideoAccountsHealthService {

    @Autowired
    private RedisService redisService;

    @Override
    public List<VideoAccountsHealth> searchAll() {
        Set<String> keys = redisService.getAll(String.format(AccountsConstant.VIDEO_ACCOUNTS_HEALTH_LOG, "*"));
        List<String> list = redisService.multiGet(keys);
        return list.stream().map(item -> JSONObject.parseObject(item, VideoAccountsHealth.class)).collect(Collectors.toList());
    }

    @Override
    public VideoAccountsHealth searchOne(String id, String platform) {
        String valueByKey = redisService.getValueByKey(String.format(AccountsConstant.VIDEO_ACCOUNTS_HEALTH_LOG, id + "_" + platform));
        if (valueByKey != null) {
            return JSONObject.parseObject(valueByKey, VideoAccountsHealth.class);
        }

        return null;
    }


    @Override
    public Boolean add(VideoAccountsHealth accountsHealth) {
        String client;
        if (StringUtils.isBlank(accountsHealth.getClient())) {
            client = ClientEnum.CREATOR.getType();
        } else {
            client = accountsHealth.getClient();
        }
        redisService.setKey(String.format(AccountsConstant.VIDEO_ACCOUNTS_HEALTH_LOG, accountsHealth.getId() + "_" + accountsHealth.getPlatform() + "_" + client),
                JSON.toJSONString(accountsHealth));
        return true;
    }

    @Override
    public Boolean isAccountsExist(VideoAccountsHealth accountsHealth) {
        return redisService.existsKey(String.format(AccountsConstant.VIDEO_ACCOUNTS_HEALTH_LOG, accountsHealth.getId() + "_" + accountsHealth.getPlatform()));
    }

    @Override
    public boolean deleteById(String id) {
        Set<String> keys = redisService.getAll(String.format(AccountsConstant.VIDEO_ACCOUNTS_HEALTH_LOG, id + "_*"));
        redisService.deleteKey(keys);
        return true;
    }
}
